package com.oos.zone.wechat.ma.controller;

import com.oos.zone.wechat.ma.service.WechatMaEventNoticeService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 功能描述：微信小程序通知事件接收
 *
 * @author 拓金辉
 * @version 1.0
 * @date 2021-07-22 13:29:30
 * @see <a href="https://work.weixin.qq.com/api/doc/10514">接收消息与事件</>
 */
@RestController
@RequestMapping("/wechat/ma/event/notice/")
public class WechatMaEventNoticeController {

    @Resource
    private WechatMaEventNoticeService wechatMaEventNoticeService;

    /**
     * 方法描述：微信通知事件
     *
     * @param signature    微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp    时间戳
     * @param nonce        随机数
     * @param openId       微信用户在公众号appid下的唯一用户标识
     * @param encryptType  加密类型
     * @param msgSignature 微信加密签名，msg_signature结合了开发者填写的token、请求中的timestamp、nonce参数、加密的消息体
     * @param appId        应用id
     * @param request      请求ServletRequest
     * @return java.lang.String
     *
     * @author 拓金辉
     * @date 2021-07-30 14:37:07
     */
    @PostMapping(value = "/{appId}")
    public String notice(@RequestParam(value = "signature") String signature,
                         @RequestParam(value = "timestamp") String timestamp,
                         @RequestParam(value = "nonce") String nonce,
                         @RequestParam(value = "openid") String openId,
                         @RequestParam(value = "encrypt_type", required = false) String encryptType,
                         @RequestParam(value = "msg_signature", required = false) String msgSignature,
                         @PathVariable(value = "appId") String appId,
                         final HttpServletRequest request) {
        return wechatMaEventNoticeService.notice(signature, timestamp, nonce, openId, encryptType, msgSignature, appId, request);
    }

    /**
     * 方法描述：验证URL有效性
     *
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echoStr   回文体，需要解密得到消息内容明文，解密后有random、msg_len、msg、CorpID四个字段，其中msg即为消息内容明文
     * @param appId     应用id
     * @param request   请求ServletRequest
     * @return java.lang.String
     *
     * @author 拓金辉
     * @date 2021-07-30 14:37:07
     */
    @GetMapping(value = "/{appId}")
    public String notice(@RequestParam(value = "signature") String signature,
                         @RequestParam(value = "timestamp") String timestamp,
                         @RequestParam(value = "nonce") String nonce,
                         @RequestParam(value = "echostr") String echoStr,
                         @PathVariable(value = "appId") String appId,
                         final HttpServletRequest request) {
        return wechatMaEventNoticeService.notice(signature, timestamp, nonce, echoStr, appId, request);
    }

}
